Skip to content

feat(perps-controller): give each exchange its own balance, positions and charts - #11461

Merged
geositta merged 30 commits into
mainfrom
TAT-4392-exchange-each-its-own
Nov 18, 2026
Merged

geositta merged 30 commits into
mainfrom
TAT-4392-exchange-each-its-own

Conversation

@geositta

@geositta geositta commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Explanation

In aggregated mode, list reads (positions, orders, fills, markets) already fan out to every venue and tag rows with providerId. Account-level data did not: getAccountState and subscribeToAccount read only the default venue, perpsBalances was declared but never written, batch cancel/close were refused outright in multi-venue mode, several market streams ignored explicit routes, and money-movement routes and records carried no venue identity. A Lighter chart would show Hyperliquid candles and the second venue's balance was invisible.

This PR gives each exchange its own account data and routing. Direct/single-provider modes keep their established behavior, and one-venue aggregated fallback (for example Hyperliquid-only while Lighter fails to load) keeps passing the direct result through unchanged.

Aggregated account reads and streams

  • AggregatedPerpsProvider.getAccountState fans out to every enabled venue and returns:
    • top-level totalBalance, spendableBalance, withdrawableBalance, marginUsed and unrealizedPnl as decimal-safe combined totals over the venues that reported data (bignumber.js, never binary float), and
    • returnOnEquity as the margin-weighted combined rate 100 × Σ unrealizedPnl ÷ Σ marginUsed ('0' when no margin is used). Both venues' adapters report account-level RoE in percentage points, so the combined rate uses the same units; it is never summed or averaged.
  • New optional providerStates entries, keyed by provider id, hold each venue's own snapshot — including venue-local crossMarginSummary and subAccountBreakdown, which are never merged into the top level because cross-venue collateral is not mutually usable. Identical sub-account names at different venues do not collide.
  • New optional aggregate metadata ({ status: 'complete' | 'partial', availableProviders, unavailableProviders, pendingProviders? }) says whether the totals cover every enabled venue. A venue whose read failed is an explicit unavailable entry — never a zero balance; a confirmed zero or nonexistent venue account is an available entry with zero balances. A stream venue that has not reported yet, including a first null, is pending. A partial total is a subtotal and must not be presented as the complete portfolio value. When no venue has usable data the read throws (REST) or the stream emits null — never an all-zero total. Aggregated reads pass throwOnUnavailable: true. HyperLiquid rejects the read when any DEX clearinghouse read or the spot clearinghouse read fails, so that venue is unavailable and the combined total is partial. Aggregated streams apply the same rule through the new SubscribeAccountParams.requireCompleteAccount: HyperLiquid emits null until every configured DEX has published on the current connection (after a reconnect, until each DEX republishes) and its spot balance has loaded, so a failed DEX subscription keeps HyperLiquid pending (or unavailable after a snapshot) and the total partial, instead of streaming the reachable DEXs' total as HyperLiquid's complete balance. Direct and single-venue streams keep the lenient total.
  • The aggregated result carries no venue providerId; per-venue attribution lives in providerStates. Each entry's venue is captured before the venue request is awaited, so a default change mid-request never mislabels a balance.
  • AggregatedPerpsProvider.subscribeToAccount subscribes to every enabled venue through the multiplexer and emits the same combined contract. The account stream is venue fan-out, not default-routed: changing the routing default neither drops a venue's subscription nor erases a still-valid all-venue total, and no null invalidation is emitted on a default change. Before a venue's first snapshot, a null update leaves it pending and keeps its persisted balance. After a snapshot, null makes it unavailable and drops that balance; it is never recorded as zero. The callback's optional second argument carries AccountAggregateMetadata even when the combined state is null, so pending and unavailable venues stay distinguishable. Each simultaneous account subscription owns its venue cache, so one subscription's cleanup never erases another subscription's venue data.

Controller state

  • perpsBalances[providerId] is now written from live account updates: one entry per available venue with totalBalance, unrealizedPnl and lastUpdated. accountValue1dAgo is optional and stays unset on live updates. Entries are cleared when the selected account changes or the network is toggled, and a stream for an explicit accountId other than the selected account only reaches its own callback: it neither writes nor clears accountState or these entries. A venue whose data becomes unavailable has its entry removed rather than left looking live. There is no synthetic combined entry; the total lives in accountState.
  • REST account responses are validated against the live account context: an aggregate result stays current while the aggregated wrapper is the active provider (regardless of the routing default); a single-venue result is matched against the venue it names. A response that resolves after the active provider changed is discarded instead of overwriting the live snapshot.
  • User-data preload assigns each venue's account state to its own provider cache bucket; the combined total is never stored in Hyperliquid's bucket merely because the aggregate has no providerId.
  • setDefaultProvider clears only a single-venue snapshot (for example a one-venue fallback read); an all-venue aggregate snapshot stays valid across the change.

Batch routing

  • cancelOrders and closePositions are venue-attributed rather than refused. Cancel-all reaches every venue that holds an order, and each cancel keeps the venue identity of the order it came from. Scoped orders targets ({ orderId, providerId }) match on both fields; bare orderIds or symbols filters are refused while more than one venue is registered (see below). closePositions takes explicit targets of { symbol, providerId }, which take precedence over closeAll and symbols, or closeAll (fans out to every enabled venue). An empty targets list closes nothing; it never falls through to close-all. An omitted or empty legacy symbols list still closes every position, as in 24.x. Selection precedence lives in resolveCloseSelection / resolveCancelSelection, shared by the controller, TradingService and both providers.
  • A batch that is incomplete returns error: BATCH_INCOMPLETE with structured detail instead of a raw message: failures ({ providerId, error }[]) on ClosePositionsResult and CancelOrdersResult for venue batches that threw or returned an error, and discoveryFailures on CancelOrdersResult for venues or order IDs whose open orders could not be read. Completion checks must look at these fields, not success alone.
  • Venue identity is execution identity: untagged batch targets are refused with PROVIDER_ROUTE_REQUIRED while multiple venues are registered (single-venue fallback accepts them), and duplicate symbols/order ids across venues are never resolved by choosing the default provider. Results carry a providerId per item, and one venue's failure never hides another venue's successes; a thrown venue batch is reported as an explicit per-venue failure.
  • Read-only account guards, stale-response handling and the other trade safety checks are unchanged.

Venue-specific market streams and money movement

  • subscribeToCandles, subscribeToOICaps and subscribeToOrderBook take an optional providerId. An explicit route reaches that venue — required when both venues list the same symbol — and stays pinned when the routing default changes. Omitting it keeps the previous default-routed rebinding behavior. An unregistered route is reported as a bare PROVIDER_NOT_FOUND error through onError (or thrown when there is no onError) and never silently subscribes to a different venue.
  • getDepositRoutes and getWithdrawalRoutes return every active venue's routes, each tagged with a providerId; identical asset/chain routes from different venues are distinct entries and are never collapsed.
  • depositWithConfirmation selects the explicit providerId, otherwise the routing default, and fails closed when that venue has no route. Deposit and withdrawal request records capture that venue before any asynchronous preparation and never relabel it. Legacy persisted records without venue identity keep their shape.

Breaking package compatibility

This is a breaking change, following the breaking-change process:

  • The aggregated AccountState semantics changed: the top-level numeric fields are now combined totals (with providerStates/aggregate when the aggregated producer ran), and the account stream no longer follows the default venue or emits a null snapshot when the default changes. The new fields are optional, but clients that keyed on the top-level providerId of an aggregated read, presented the top level as a single venue's balance, or relied on default-change invalidation must read per-venue values from providerStates and partial-total obligations from aggregate.
  • perpsBalances entries made accountValue1dAgo optional and gain entries at runtime (previously declared, never written). Client state readers, typed defaults and fixtures that model the entry as fully required need updating.
  • ClosePositionsParams gains optional targets, BatchCancelOrdersParams entries gain optional providerId, SubscribeAccountParams gains optional requireCompleteAccount, and the batch/stream/route result types gain optional providerId fields. All additive.
  • New package exports: PerpsProviderAccountStateEntry, AccountAggregateMetadata, ClosePositionsTarget. New subpath exports: @metamask/perps-controller/utils/cancelOrders, /utils/closePositions and /utils/feeSupport (selection and fee-support helpers).

The full consumer inventory, migration notes and unavailability semantics are in the package CHANGELOG.md (Unreleased) and the package README's "Per-exchange account data" section.

Client plan

Client draft PRs are not opened yet; scope is ticketed.

Client Plan Ticket
Mobile Default provider and per-trade venue compatibility TAT-4405
Mobile Per-provider streams and balances adoption TAT-4407
Extension Checked at 803491c (@metamask/perps-controller ^22.3.0): runs HyperLiquid direct mode with no Lighter or multi-provider wiring, and a one-venue aggregated wrapper passes results through unchanged. The only observable change is that perpsBalances.hyperliquid is now populated; hyperliquid-deposit/eligibility.ts reads it as an extra zero-balance check that agrees with accountState. No change needed now; multi-venue adoption must read providerStates in deposit eligibility and filter getWithdrawalRoutes by providerId on the withdraw page. —
Terminal Terminal-backend account reads were checked at b61ee0d: no @metamask/perps-controller dependency and none of the changed surfaces are consumed; no changes needed. —

Evidence

  • Full @metamask/perps-controller suite with coverage at 21f7b82: 143 files, 7,660 passed, 40 skipped; coverage thresholds pass (92.45% lines). docs/architecture.md describes per-venue account data, batch routing and the new error surface. Per-package suite only; the monorepo suite was not run.
  • Root yarn lint:tsc:check reports no new type errors; oxlint and oxfmt --check on every changed file, yarn changelog:validate, and the package build are clean.
  • The released ## [24.1.0] and older changelog sections are byte-identical to main; every entry from this PR is under ## [Unreleased], including the five BREAKING entries.
  • HyperLiquid partial accounts have end-to-end coverage: a real HyperLiquidProvider with a failing HIP-3 DEX inside AggregatedPerpsProvider yields aggregate.status: 'partial' with HyperLiquid unavailable (REST), and a real HyperLiquidSubscriptionService whose HIP-3 DEX subscription fails keeps the aggregated stream partial (verified to fail without requireCompleteAccount).
  • Deposit route selection is settled: depositWithConfirmation uses the explicit providerId or the routing default and fails closed when that venue has no route.

References

  • Ticket: TAT-4392 — give each exchange its own balance, positions and charts.
  • Depends on: TAT-4385, default provider and explicit per-trade routing (#11421).
  • Unblocks: TAT-4405, TAT-4407.
  • Related: TAT-4329 (cross-margin summary and explicit unavailable result for Lighter account reads), TAT-4406 (Lighter money movement).

Checklist

  • I've updated the test suite for new or updated code as appropriate
  • I've updated documentation (JSDoc, Markdown, etc.) for new or updated code as appropriate
  • I've communicated my changes to consumers by updating changelogs for packages I've changed
  • I've introduced breaking changes in this PR and have prepared draft pull requests for clients and consumer packages to resolve them

Note

High Risk
Breaking aggregated account and batch-close/cancel contracts touch balances, margin totals, and multi-venue execution paths where mis-handling could show wrong portfolio values or cancel/close on the wrong venue.

Overview
Aggregated perps mode now treats each exchange as a first-class data source instead of hiding everything behind the routing default. getAccountState and subscribeToAccount fan out to every enabled venue and return combined decimal-safe totals plus providerStates and aggregate completeness metadata; streams use requireCompleteAccount so partial HyperLiquid or Lighter reads are marked partial/unavailable rather than shown as a full portfolio. perpsBalances is populated per providerId from live updates (with optional accountValue1dAgo), and controller state clears or isolates balances on account, network, or provider topology changes.

Batch cancel/close and money movement are venue-routed. Multi-venue cancelOrders and closePositions fan out or honor { providerId, … } targets; legacy bare orderIds/symbols filters still require an explicit route when multiple venues are registered. Results expose BATCH_INCOMPLETE, per-venue failures, and cancel discovery failures; strict open-order reads can throw OrderDiscoveryError. Deposits/withdrawals list all venues' routes, depositWithConfirmation fails closed on the chosen venue, and request records store an initiating providerId. Market streams (subscribeToCandles, OI caps, order book) accept optional providerId pinning.

New shared helpers (accountAggregation, cancelOrders, closePositions, feeSupport) back the aggregated provider, controller cache/preload, and docs/changelog updates. Several breaking consumer contracts: aggregated AccountState shape, deposit/withdrawal route lists, default-change behavior for account subscriptions, and multi-venue batch semantics.

Reviewed by Cursor Bugbot for commit e80f01d. Bugbot is set up for automated code reviews on this repo. Configure here.

@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🛑 Files requiring codeowner review

To merge this PR, you'll need to get approvals from the following owners.

@MetaMask/perps (52 files)
  • packages/perps-controller/CHANGELOG.md
  • packages/perps-controller/docs/architecture.md
  • packages/perps-controller/README.md
  • packages/perps-controller/src/aggregation/SubscriptionMultiplexer.ts
  • packages/perps-controller/src/errors.ts
  • packages/perps-controller/src/index.ts
  • packages/perps-controller/src/PerpsController.ts
  • packages/perps-controller/src/perpsErrorCodes.ts
  • packages/perps-controller/src/providers/AggregatedPerpsProvider.ts
  • packages/perps-controller/src/providers/HyperLiquidProvider.ts
  • packages/perps-controller/src/providers/LighterProvider.ts
  • packages/perps-controller/src/services/AccountService.ts
  • packages/perps-controller/src/services/DepositService.ts
  • packages/perps-controller/src/services/HyperLiquidSubscriptionService.ts
  • packages/perps-controller/src/services/RewardsIntegrationService.ts
  • packages/perps-controller/src/services/ServiceContext.ts
  • packages/perps-controller/src/services/TradingService.ts
  • packages/perps-controller/src/types/index.ts
  • packages/perps-controller/src/utils/accountAggregation.ts
  • packages/perps-controller/src/utils/accountUtils.ts
  • packages/perps-controller/src/utils/cancelOrders.ts
  • packages/perps-controller/src/utils/closePositions.ts
  • packages/perps-controller/src/utils/feeSupport.ts
  • packages/perps-controller/src/utils/standaloneInfoClient.ts
  • packages/perps-controller/tests/public-api-types.ts
  • packages/perps-controller/tests/src/aggregation/SubscriptionMultiplexer.test.ts
  • packages/perps-controller/tests/src/PerpsController.configuration.test.ts
  • packages/perps-controller/tests/src/PerpsController.default-provider.test.ts
  • packages/perps-controller/tests/src/PerpsController.lifecycle.test.ts
  • packages/perps-controller/tests/src/PerpsController.operations.test.ts
  • packages/perps-controller/tests/src/PerpsController.providers-cache.test.ts
  • packages/perps-controller/tests/src/PerpsController.subscriptions.test.ts
  • packages/perps-controller/tests/src/PerpsController.trading.test.ts
  • packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.discovery.test.ts
  • packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.test.ts
  • packages/perps-controller/tests/src/providers/HyperLiquidProvider.error-handling.test.ts
  • packages/perps-controller/tests/src/providers/HyperLiquidProvider.history.test.ts
  • packages/perps-controller/tests/src/providers/HyperLiquidProvider.standalone.test.ts
  • packages/perps-controller/tests/src/providers/HyperLiquidProvider.trading.test.ts
  • packages/perps-controller/tests/src/providers/LighterProvider.order-validation.test.ts
  • packages/perps-controller/tests/src/providers/LighterProvider.reads-and-orders.test.ts
  • packages/perps-controller/tests/src/providers/LighterProvider.streaming-and-session.test.ts
  • packages/perps-controller/tests/src/services/AccountService.test.ts
  • packages/perps-controller/tests/src/services/DepositService.test.ts
  • packages/perps-controller/tests/src/services/HyperLiquidSubscriptionService.cache.test.ts
  • packages/perps-controller/tests/src/services/RewardsIntegrationService.test.ts
  • packages/perps-controller/tests/src/services/TradingService.test.ts
  • packages/perps-controller/tests/src/utils/accountAggregation.test.ts
  • packages/perps-controller/tests/src/utils/accountUtils.test.ts
  • packages/perps-controller/tests/src/utils/cancelOrders.test.ts
  • packages/perps-controller/tests/src/utils/closePositions.test.ts
  • packages/perps-controller/tests/src/utils/feeSupport.test.ts

ℹ️ Files co-owned by @MetaMask/core-platform (expand for more)

[!NOTE]
For convenience in maintaining this repo, @MetaMask/core-platform co-owns
the following files. It is not required to seek approval from
@MetaMask/core-platform to change these files. This section is purely
informational.

  • packages/perps-controller/CHANGELOG.md

@geositta
geositta marked this pull request as ready for review November 13, 2026 05:17
@geositta
geositta requested review from a team as code owners November 13, 2026 05:17

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@geositta geositta changed the title feat(perps-controller): give each exchange its own balance, positions… feat(perps-controller): give each exchange its own balance, positions and charts Nov 13, 2026
@geositta
geositta force-pushed the TAT-4392-exchange-each-its-own branch from 8d65ac0 to d1b138e Compare November 13, 2026 06:35

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@geositta
geositta force-pushed the TAT-4392-exchange-each-its-own branch from 067b22a to 32c9103 Compare November 13, 2026 07:26

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@abretonc7s abretonc7s left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: REQUEST_CHANGES
COMMIT: 2ef9bbc

The fan-out, batch routing and per-venue attribution are solid and well tested. Two confirmed Perps anti-patterns sit in the new aggregation helper, and the pending/unavailable contract is documented three different ways.
⚠️ NOT_CHECKED: Terminal consumer (no checkout supplied).

Severity file:line Problem Ask
❌ Major packages/perps-controller/src/utils/accountAggregation.ts:71 Combined sum and RoE duplicate exported aggregateAccountStates, and the decimal fix lands in one copy only. Share one helper.
❌ Major packages/perps-controller/src/utils/accountAggregation.ts:52 ?? '0' zero-fills a missing venue field; a non-numeric field turns every total into 'NaN'. Classify invalid venue data as unavailable.
⚠️ Minor packages/perps-controller/src/providers/AggregatedPerpsProvider.ts:2017 First-null venue stays pending against the type/README/CHANGELOG wording; an all-pending null wipes perpsBalances. Pick one rule; keep pending entries.
⚠️ Minor packages/perps-controller/src/services/TradingService.ts:2145 Filtered orderIds cancel hits the same id on both venues. Venue-scope ids or pin with a test.
⚠️ Minor packages/perps-controller/CHANGELOG.md:46 Breaking change under Added without **BREAKING:**/PR link; intra-PR "Fixed" entries. Follow the file's breaking-entry format.
💬 Nit packages/perps-controller/src/providers/AggregatedPerpsProvider.ts:2148 as unknown as PerpsProvider stub. Return a no-op unsubscribe directly.
💬 Nit packages/perps-controller/src/utils/accountAggregation.ts:64 JSDoc says "PnL-weighted". Say "margin-weighted".
Details for agents
Status Item Evidence or gap Ask
⚠️ Minor PR description and client plan The open deposit question (depositRoutes[0]) no longer matches DepositService.#selectDepositRoute. Extension (ref 4c9c2d3c) reads perpsBalances and types accountValue1dAgo as required, but has no row in the client plan. Update the description and add an Extension row.
⚠️ NOT_CHECKED Terminal consumer No Terminal checkout among the frozen references; the PR's b61ee0d claim is unverified. None (reviewer-side gap).

➖ 10 checklist rules not applicable to this diff; full ledger in the run artifacts: artifacts/review-ledger.md.

Diff scope

File Ticket AC or required test Scope justification or finding
packages/perps-controller/CHANGELOG.md TAT-4392 breaking-change process In scope; release notes for this change. Finding: entry placement/wording (CHANGELOG.md:46).
packages/perps-controller/README.md TAT-4392 documentation In scope; per-exchange account data section. Finding: pending/unavailable wording disagrees with code (AggregatedPerpsProvider.ts:2017).
packages/perps-controller/src/PerpsController.ts TAT-4392 perpsBalances, stale-response checks, batch routing, deposit attribution In scope.
packages/perps-controller/src/aggregation/SubscriptionMultiplexer.ts TAT-4392 per-subscription account cache In scope.
packages/perps-controller/src/index.ts TAT-4392 new public types In scope; exports PerpsProviderAccountStateEntry, AccountAggregateMetadata, ClosePositionsTarget.
packages/perps-controller/src/providers/AggregatedPerpsProvider.ts TAT-4392 fan-out reads/streams, batch routing, routes In scope. Findings at 2017 (minor) and 2148 (nit).
packages/perps-controller/src/providers/HyperLiquidProvider.ts TAT-4392 tagged close targets In scope; closes only targets naming HyperLiquid.
packages/perps-controller/src/providers/LighterProvider.ts TAT-4392 per-venue account data In scope; null on rebinding and best-effort crossMarginSummary keep strict aggregate reads from dropping Lighter balances.
packages/perps-controller/src/services/AccountService.ts TAT-4392 withdrawal venue attribution In scope.
packages/perps-controller/src/services/DepositService.ts TAT-4392 deposit route selection and attribution In scope.
packages/perps-controller/src/services/TradingService.ts TAT-4392 venue-attributed batch cancel/close and per-venue fees In scope. Finding at 2145 (minor).
packages/perps-controller/src/types/index.ts TAT-4392 public types In scope.
packages/perps-controller/src/utils/accountAggregation.ts TAT-4392 combined totals In scope. Findings at 71 and 52 (major), 64 (nit).
packages/perps-controller/tests/public-api-types.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/PerpsController.configuration.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/PerpsController.default-provider.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/PerpsController.operations.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/PerpsController.subscriptions.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/providers/HyperLiquidProvider.trading.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/providers/LighterProvider.order-validation.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/providers/LighterProvider.reads-and-orders.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/providers/LighterProvider.streaming-and-session.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/services/AccountService.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/services/DepositService.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
packages/perps-controller/tests/src/services/TradingService.test.ts Required test for TAT-4392 behavior In scope; tests the changed controller/provider/service behavior (inspected, not executed).
tsc-suppressions.json Required test: AggregatedPerpsProvider.test.ts type fixes Sensitive path inspected: removes only the stale TS2304 suppression count for the touched AggregatedPerpsProvider.test.ts (repo lint:tsc:prune workflow). Tightens the baseline; no tooling behavior change; not a scope finding.

Additional findings

  • [minor] packages/perps-controller/src/PerpsController.ts: PR description and client plan are out of date. (1) The "open policy question" says the aggregated deposit flow takes depositRoutes[0], the first registered venue; the code now picks the explicit providerId, else the routing default, and fails closed (DepositService.#selectDepositRoute). (2) The client plan lists Mobile and Terminal but not Extension, which consumes perpsBalances (ui/selectors/perps-controller.ts, app/scripts/lib/hyperliquid-deposit/eligibility.ts) and types accountValue1dAgo as a required string in ui/__mocks__/perps/perps-controller/index.ts:1285 (extension ref 4c9c2d3c). Ask: update the description to the shipped deposit behavior and add an Extension row (ticket or "no change needed" with evidence).

* @param states - Available, valid per-venue account states.
* @returns The venue-neutral combined totals.
*/
export function aggregateAccountTotals(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major. Perps anti-pattern "Copy or port of existing logic". aggregateAccountTotals re-implements the cross-state balance sum and the combined RoE formula (100 × Σ unrealizedPnl ÷ Σ marginUsed, '0' when margin used ≤ 0) that the exported aggregateAccountStates in src/utils/accountUtils.ts:471 already computes for HyperLiquid per-DEX states. The two copies already diverge: the new one is decimal-safe for marginUsed/unrealizedPnl, the old one still uses parseFloat, so the precision fix lands in only one copy. Ask: extract one shared helper for the additive fields + combined RoE (BigNumber throughout) and have both aggregateAccountStates (which then adds its cross-margin merge) and buildAggregatedAccountState call it, so the formula exists once.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b9cbf82. The additive sums and combined RoE now live once in aggregateAccountTotals (src/utils/accountAggregation.ts), BigNumber throughout; aggregateAccountStates in accountUtils.ts calls it and only adds its cross-margin merge, so the parseFloat copy is gone.

field: (typeof ADDITIVE_FIELDS)[number],
): string {
const total = states.reduce(
(acc, state) => acc.plus(new BigNumber(state[field] ?? '0')),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major. Perps anti-pattern "Missing data converted to zero". new BigNumber(state[field] ?? '0') turns a missing venue field into a confirmed zero inside the combined balance. The JSDoc above says a value that is not a finite decimal "contributes nothing", but a non-numeric string (for example the '--' fallback aggregateAccountStates returns for an empty HL state set) makes the whole sum NaN, so every top-level total becomes the string 'NaN' while aggregate.status still says the venue is available. Ask: drop the ?? '0', validate that each available venue state has finite decimal values for the additive fields, and classify a venue that fails that check as unavailable (excluded from totals and listed in aggregate.unavailableProviders). Add a test with one venue reporting a non-numeric field.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b9cbf82. ?? '0' is removed. getAccountAggregateMetadata classifies an available venue whose additive fields are missing or non-finite (including '--') as unavailable: it is excluded from the totals and listed in aggregate.unavailableProviders. Covered in tests/src/utils/accountAggregation.test.ts.

// Reported before and its latest update was null: no current
// balance is known for this venue. Never seen: it simply has
// not reported yet.
return lastReport.has(providerId)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor. The null/pending contract is documented three different ways and the controller undoes part of it. Code: a venue whose first update is null stays pending, because lastReport only remembers venues that reported data (test "keeps a pending venue pending..." pins this). Docs: PerpsProviderAccountStateEntry JSDoc (src/types/index.ts:1006), CHANGELOG line 75 and the PR description say a venue whose latest update was null is unavailable; README line 107 says a venue that has not reported yet is unavailable and never mentions pending. Separately, if the first emission of the stream is a null (all venues pending), buildAggregatedAccountState returns null and PerpsController sets perpsBalances = {} (src/PerpsController.ts:7642), which wipes the persisted entries the pending status exists to protect. Ask: pick one rule (for example "null before any data is unavailable", or keep pending and say so), make the type JSDoc, README and CHANGELOG match, and keep pending venues' entries in the all-pending null path (only clear entries of venues that were explicitly unavailable). Add a controller test where the first update is a null.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b9cbf82. One rule everywhere: before a venue's first snapshot it is pending (including on null); after a snapshot, null makes it unavailable. The type JSDoc, README and CHANGELOG now say this. The stream callback's second argument carries AccountAggregateMetadata even when the combined state is null, and PerpsController removes only aggregate.unavailableProviders entries in that case, so pending venues keep their persisted balances. Controller test: "preserves pending balances when the first account emission is null".

}

// Use batch cancel if provider supports it
// Use batch cancel if provider supports it. Each target keeps the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor. Entity ownership: filtered cancelOrders({ orderIds }) selects orders with params.orderIds?.includes(order.orderId) over the aggregated order list, so if HyperLiquid and Lighter both hold an order with the same id, a filtered cancel of one also cancels the other. Each matched order keeps its own venue tag, so both venues receive a cancel. The PR states duplicate order ids across venues are never conflated, and the Perps rule asks for a colliding-id test; none exists (the mixed-venue tests use distinct ids). Ask: accept venue-scoped ids for a filtered cancel (for example orders: { orderId, providerId }[], or reuse BatchCancelOrdersParams) and match on both fields, or add a test that pins and documents the cross-venue behavior.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b9cbf82 and ef86cb0. CancelOrdersParams.orders takes { orderId, providerId } targets matched on both fields, and a bare orderIds (or symbols) filter is refused with PROVIDER_ROUTE_REQUIRED while more than one venue is registered (getUnroutedCancelOrdersRefusal), so a colliding ID can no longer cancel the other venue's order. Colliding-ID tests use the same ID on both venues.

Comment thread packages/perps-controller/CHANGELOG.md Outdated
- Hyperliquid and Lighter implement both on testnet and mainnet with the same `PublicTrade` shape: `{ id, symbol, price, size, side, timestamp, txHash?, providerId }`, where `side` is the aggressor's (`buy` or `sell`). `AggregatedPerpsProvider` routes to `providerId`, else the default provider. Like `subscribeToCandles`, an unrouted stream moves to the new default when `setDefaultProvider` changes it, and an unrouted read resolves to `[]` if the default changes before the venue answers
- New optional `PerpsProvider.getPublicTrades` and `PerpsProvider.subscribeToPublicTrades` members, and types `PublicTrade`, `GetPublicTradesParams`, `SubscribePublicTradesParams`, `PerpsControllerGetPublicTradesAction` and `PerpsControllerSubscribeToPublicTradesAction`
- Subpath exports `@metamask/perps-controller/constants/lighterConfig` and `@metamask/perps-controller/utils/*` also expose `LIGHTER_RECENT_TRADES_MAX_LIMIT`, `buildPublicTrade`, `sortPublicTradesNewestFirst`, `PublicTradeFields`, `adaptPublicTradesFromHyperLiquid` and `adaptPublicTradesFromLighter`
- Add per-exchange account data to aggregated mode: `getAccountState` and `subscribeToAccount` query every enabled venue and expose each venue's state separately plus a correctly identified combined total (**BREAKING**: the aggregated result shape changed)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor. Release metadata does not follow the repo changelog conventions. (1) The breaking aggregated AccountState change sits under ### Added with a trailing "(BREAKING: ...)" instead of a ### Changed entry starting with **BREAKING:**, which is how every other breaking entry in this file is written (e.g. line 66). (2) Making perpsBalances[*].accountValue1dAgo optional is a type-breaking change for state readers and is not marked breaking. (3) The new Added entries at lines 46-62 have no PR link. (4) Fixed entries at lines 75, 85, 86, 87 and 89 describe fixes to behavior that only exists in this unreleased PR (pending vs unavailable, tagged targets, thrown multi-venue close, first enumerated deposit route, one-venue fallback vs combined snapshot); released consumers never saw those bugs. Ask: move the breaking items to ### Changed with the **BREAKING:** prefix and the PR link, mark the accountValue1dAgo change breaking, and fold the intra-PR "Fixed" entries into the Added/Changed descriptions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b9cbf82 (refined in later commits). Breaking items are under ### Changed with the **BREAKING:** prefix and PR links, accountValue1dAgo optionality has its own BREAKING entry, every Unreleased entry links its PR, and the intra-PR "Fixed" entries were folded into the Added/Changed descriptions.

subscribeToCandles: () => () => undefined,
subscribeToOICaps: () => () => undefined,
subscribeToOrderBook: () => () => undefined,
} as unknown as PerpsProvider;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit. #resolveExplicitStreamRoute builds a stub with as unknown as PerpsProvider for the unregistered-route case. A double assertion hides the stub's real type. Ask: have the three subscribe methods return a no-op unsubscribe directly when the route is missing (e.g. a #reportMissingStreamRoute(params): (() => void) | undefined helper), without the cast.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b9cbf82. #resolveExplicitStreamRoute returns undefined after reporting the missing route through onError, and each subscribe method falls back to a no-op unsubscribe; there is no stub provider or double assertion. (93e81ad also passes onError directly instead of a params union.)

* Additive USD fields are decimal-summed. `returnOnEquity` is a rate, not a
* balance: both venues report account-level RoE in percentage points
* (unrealized PnL relative to margin used), so the combined rate is
* `100 x sum(unrealizedPnl) / sum(marginUsed)` — PnL-weighted, never summed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit. JSDoc calls the combined RoE "PnL-weighted"; 100 × Σ unrealizedPnl ÷ Σ marginUsed is margin-weighted, as the README and CHANGELOG say. Ask: change the wording to "margin-weighted".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b9cbf82. The JSDoc now says margin-weighted, matching the README and CHANGELOG.

@juanmigdr

Copy link
Copy Markdown
Member

Heads up for when this is bumped in metamask-mobile. Our two-exchange test presets (metamask-mobile#39846) have one line that will make yarn lint:tsc fail once Mobile uses a perps-controller version with AccountState.providerStates.

It's the line marked @ts-expect-error TAT-4392 in tests/component-view/presets/perpsTwoExchangePresets.ts. To fix it:

  1. Delete that line and the type alias under it.
  2. Give each scenario per-exchange providerStates and aggregate. For lighterDown, Lighter should be unavailable.

Nothing else should break. If providerStates gets renamed during review, the check won't fire, so please ping me.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@geositta
geositta force-pushed the TAT-4392-exchange-each-its-own branch from 65c4337 to 706991b Compare November 17, 2026 03:21

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@abretonc7s abretonc7s left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: REQUEST_CHANGES
COMMIT: 776b9a4

The missing helper modules are now committed with tests, and the changelog is fixed. One major problem remains: the aggregated account total can report complete while HyperLiquid has returned a partial balance.
⚠️ NOT_CHECKED: no tests or builds were run (static review). Terminal had no reference checkout.
Since last review: ✅ resolved TradingService.ts:50 (missing cancelOrders/feeSupport modules, now with unit tests plus the shared resolveCloseSelection); ✅ resolved CHANGELOG.md:89 (intra-PR fixes folded into Added/Changed); ❌ still open AggregatedPerpsProvider.ts:711; ⚠️ still open README.md:170 and the PR description; 💬 still open PerpsController.ts:4381, :7580.

Severity file:line Problem Ask
❌ Major packages/perps-controller/src/providers/AggregatedPerpsProvider.ts:711 HyperLiquid ignores throwOnUnavailable for account state. A failed HIP-3 DEX or spot read is labeled available, and the total is reported as complete. Make HyperLiquid honor strict account reads, or mark that venue partial or unavailable. Add a test.
⚠️ Minor packages/perps-controller/README.md:170 The README says balance entries record accountAddress/isTestnet and carry accountValue1dAgo forward; the code does neither. The targets JSDoc also omits that targets take precedence over closeAll. Make the docs match the code.
⚠️ Minor PR description The description says null makes a venue unavailable and that accountValue1dAgo is carried forward. It still lists the depositRoutes[0] question as open, and its evidence predates the current head. Update the description and re-record the evidence on 776b9a4.
💬 Nit packages/perps-controller/src/PerpsController.ts:4381 The deposit venue-attribution comment repeats the comment at :4362. Keep one.
💬 Nit packages/perps-controller/src/PerpsController.ts:7580 The pending comment is broken mid-sentence across lines. Reflow it.
Details for agents
Status Item Evidence or gap Ask
⚠️ NOT_CHECKED Runtime and test execution Static review only: no build, tsc or vitest run on 776b9a4. Supply CI for this head.
⚠️ NOT_CHECKED Terminal consumer No Terminal reference checkout was supplied. —
✅ Delta check resolveCancelSelection, getUnroutedCancelOrdersRefusal, resolveCloseSelection, hasFeeSetter Each matches the inline logic it replaces. Close selection is now one exhaustive selector shared by the controller guard, aggregated execution, HyperLiquid execution, fee pricing and the per-position fallback. —

➖ Rules not applicable to this diff (UI, i18n, Pro mode, MetaMetrics, navigation, embedded signer, formatter, multi-sig, unified account) are recorded in artifacts/review-ledger.md.

Diff scope

File Ticket AC or required test Scope justification or finding
packages/perps-controller/CHANGELOG.md Ticket: breaking-change process and changelog for consumers In scope. Prior finding resolved: intra-PR fixes are folded into Added/Changed. The remaining Fixed entries describe 24.0.0 behavior (non-finite skip in batch-close pricing, Lighter wallet scope, HIP-3 cancel discovery, Lighter cancel fallback, decimals, empty filters, Lighter zero emission).
packages/perps-controller/README.md Ticket: "Per-exchange account data" README section named in the PR In scope. FINDING (minor, still open): provenance and carry-forward claims contradict code.
packages/perps-controller/src/PerpsController.ts Ticket: perpsBalances writes, REST validation, preload buckets, setDefaultProvider, batch routing, deposit attribution In scope. Delta adds resolveCloseSelection for the legacy symbols refusal. Two comment nits still open.
packages/perps-controller/src/aggregation/SubscriptionMultiplexer.ts Ticket: per-subscription account venue cache and fan-out In scope; unchanged in delta.
packages/perps-controller/src/errors.ts Ticket: venue-attributed batch discovery (OrderDiscoveryError) In scope; unchanged in delta.
packages/perps-controller/src/index.ts Ticket: new package exports In scope; unchanged in delta.
packages/perps-controller/src/perpsErrorCodes.ts Ticket: batch routing results (BATCH_INCOMPLETE) In scope; unchanged in delta.
packages/perps-controller/src/providers/AggregatedPerpsProvider.ts Ticket: aggregated account reads/streams, batch routing, venue streams, money-movement routes In scope. Delta uses resolveCloseSelection with unchanged semantics. MAJOR (still open): the strict account read is not honored by HyperLiquid.
packages/perps-controller/src/providers/HyperLiquidProvider.ts Ticket: venue-attributed batch close targets and strict discovery In scope. Delta replaces the inline target/symbol selection with resolveCloseSelection; behavior is equivalent.
packages/perps-controller/src/providers/LighterProvider.ts Ticket: per-venue account data and strict discovery In scope; unchanged in delta.
packages/perps-controller/src/services/AccountService.ts Ticket: withdrawal records capture initiating venue In scope; unchanged in delta.
packages/perps-controller/src/services/DepositService.ts Ticket: deposit records/routes carry venue identity In scope; unchanged in delta.
packages/perps-controller/src/services/RewardsIntegrationService.ts Ticket: per-venue batch close fee resolution In scope; unchanged in delta.
packages/perps-controller/src/services/ServiceContext.ts Ticket: strict discovery for batch cancel In scope; unchanged in delta.
packages/perps-controller/src/services/TradingService.ts Ticket: venue-attributed cancelOrders/closePositions and per-venue fees In scope. Blocker resolved: imports now resolve. Delta switches fee routing and per-position fallback to exhaustive resolveCloseSelection branches with equivalent semantics.
packages/perps-controller/src/types/index.ts Ticket: AccountState providerStates/aggregate, batch and stream providerId types In scope. Minor: targets JSDoc precedence wording (see README finding).
packages/perps-controller/src/utils/accountAggregation.ts Ticket: decimal-safe combined totals and completeness metadata In scope; unchanged in delta.
packages/perps-controller/src/utils/accountUtils.ts Ticket: decimal-safe totals shared with per-DEX aggregation In scope; unchanged in delta.
packages/perps-controller/src/utils/cancelOrders.ts Ticket: batch routing (cancel selection and legacy-filter refusal); resolves prior blocker In scope. One selector shared by the controller guard and TradingService; empty filters select none; legacy orderIds/symbols are refused when more than one venue is registered (fails closed for an aggregated wrapper with unknown membership).
packages/perps-controller/src/utils/closePositions.ts Ticket: batch routing (close selection precedence) In scope. Deduplicates four inline copies of targets > closeAll > symbols > all (controller, aggregated, HyperLiquid, TradingService).
packages/perps-controller/src/utils/feeSupport.ts Ticket: per-venue batch close fee resolution; resolves prior blocker In scope. Shared fee-setter check used by the aggregated provider and TradingService.
packages/perps-controller/src/utils/standaloneInfoClient.ts Ticket: strict discovery for standalone reads In scope; unchanged in delta.
packages/perps-controller/tests/public-api-types.ts Required test: consumer-style export contracts In scope; unchanged in delta.
packages/perps-controller/tests/src/PerpsController.configuration.test.ts Required test: balances cleared on network toggle In scope.
packages/perps-controller/tests/src/PerpsController.default-provider.test.ts Required test: default change keeps the aggregate; stale responses; mixed-venue batches In scope.
packages/perps-controller/tests/src/PerpsController.lifecycle.test.ts Required test: balances cleared on provider selection change In scope.
packages/perps-controller/tests/src/PerpsController.operations.test.ts Required test: deposit venue forwarding and attribution In scope.
packages/perps-controller/tests/src/PerpsController.subscriptions.test.ts Required test: perpsBalances per venue from stream; pending/unavailable; preload buckets In scope.
packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.discovery.test.ts Required test: strict discovery, account scope, cancel discovery failures In scope.
packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.test.ts Required test: aggregated account reads, mixed-venue batch routing, explicit streams In scope. Gap: no HyperLiquid partial-DEX account-state case (major finding).
packages/perps-controller/tests/src/providers/HyperLiquidProvider.history.test.ts Required test: HyperLiquid strict discovery and partial HIP-3 orders In scope.
packages/perps-controller/tests/src/providers/HyperLiquidProvider.standalone.test.ts Required test: standalone strict reads In scope.
packages/perps-controller/tests/src/providers/HyperLiquidProvider.trading.test.ts Required test: tagged close targets on HyperLiquid In scope.
packages/perps-controller/tests/src/providers/LighterProvider.order-validation.test.ts Required test: Lighter fixture adjustments In scope.
packages/perps-controller/tests/src/providers/LighterProvider.reads-and-orders.test.ts Required test: Lighter account scope and best-effort summary In scope.
packages/perps-controller/tests/src/providers/LighterProvider.streaming-and-session.test.ts Required test: Lighter null emission on deselect In scope.
packages/perps-controller/tests/src/services/AccountService.test.ts Required test: withdrawal venue attribution In scope.
packages/perps-controller/tests/src/services/DepositService.test.ts Required test: deposit route selection In scope.
packages/perps-controller/tests/src/services/RewardsIntegrationService.test.ts Required test: reserved subscription allowance In scope.
packages/perps-controller/tests/src/services/TradingService.test.ts Required test: cancel selection, per-venue fee pricing, tagged closes In scope.
packages/perps-controller/tests/src/utils/accountAggregation.test.ts Required test: totals, RoE and metadata In scope.
packages/perps-controller/tests/src/utils/accountUtils.test.ts Required test: exact decimals in aggregateAccountStates In scope.
packages/perps-controller/tests/src/utils/cancelOrders.test.ts Required test: direct unit tests for cancel selection and refusal (asked in prior blocker) In scope. Covers precedence, empty filters, multi-venue refusal, single-venue allowance and fail-closed unknown membership.
packages/perps-controller/tests/src/utils/closePositions.test.ts Required test: close selection precedence In scope. Covers empty targets/symbols, closeAll over symbols, and targets over closeAll.
packages/perps-controller/tests/src/utils/feeSupport.test.ts Required test: fee-setter detection (asked in prior blocker) In scope.
tsc-suppressions.json Required test hygiene: PR description evidence names tsc-suppressions.json losing entries after the test-file type fixes Unchanged in delta. Removes only the TS2304 baseline for the in-scope AggregatedPerpsProvider.test.ts and adds no suppression; pruning is required by lint:tsc:check, not unauthorized tooling churn.

Additional findings

  • [major] packages/perps-controller/src/providers/AggregatedPerpsProvider.ts:711: Still open from the previous round; the 776b9a4 delta does not touch HyperLiquidProvider.getAccountState. This is Perps anti-pattern "Unknown treated as confirmed zero" in the new completeness contract. The aggregated read forces throwOnUnavailable: true on the assumption that only a genuine rejection becomes unavailable (comment above line 711), but HyperLiquidProvider.getAccountState never reads throwOnUnavailable. When one HIP-3 DEX's clearinghouseState fails, it logs "partial DEX failures" and returns the reachable DEXs' sum. When spotClearinghouseState is rejected, it returns perps-only totals without spot USDC collateral. That partial snapshot becomes { status: 'available' }. getAccountAggregateMetadata then reports status: 'complete', and the controller writes it into perpsBalances.hyperliquid as the live venue balance. The README and PR say a partial total must never be shown as the complete portfolio; this path labels a known-incomplete total as complete. Ask: make HyperLiquid honor throwOnUnavailable for account state on DEX or spot failure (or return a partial signal the aggregator maps to unavailable/partial). Add an AggregatedPerpsProvider test where HyperLiquid has one failed DEX and assert the aggregate is not complete.

  • [minor] packages/perps-controller/README.md:170: Still open (README is unchanged in this delta). README lines 170-174 say each perpsBalances entry "records the accountAddress and isTestnet it was observed for; an optional accountValue1dAgo carries forward only within that same account and network". PerpsController's writeBalance writes only totalBalance, unrealizedPnl and lastUpdated, and replaces the whole entry. There is no provenance and no carry-forward; the test 'writes live balances without carrying stale history or adding provenance' asserts exactly that, and the CHANGELOG says "Live updates do not carry historical values forward". Lines 167-168 ("Pending venues retain their persisted entries and history") overstate this as well. The ClosePositionsParams.targets JSDoc (types/index.ts:1131-1134) also says targets take precedence over symbols, while the new resolveCloseSelection (utils/closePositions.ts) gives non-empty targets precedence over closeAll too. Ask: remove the provenance and carry-forward sentences from the README and state that accountValue1dAgo is not populated by live updates. Update the targets JSDoc to say targets win over both symbols and closeAll.

  • [minor] PR description: Still open: the PR description makes claims the current head contradicts. (1) "A venue whose update is null is explicitly unavailable — its previous value is not kept": the stream keeps a venue pending on null before its first snapshot and retains its persisted balance (AggregatedPerpsProvider subscribeToAccount; PerpsController pending branch; CHANGELOG says the same). (2) "accountValue1dAgo ... is only carried forward from a real prior entry": nothing carries it forward. (3) The open question about depositRoutes[0] is stale: DepositService.#selectDepositRoute now selects the explicit providerId or the routing default and fails closed otherwise. (4) The Evidence section (7,067 tests, build and lint:tsc:check clean) predates the last two commits, which added three utility modules and three test files. The description also omits the stream callback's second argument and pendingProviders. Ask: update the description to the current contract, and re-run and re-record the evidence on 776b9a4.

  • [nit] packages/perps-controller/src/PerpsController.ts:4381: Still open: the deposit venue-attribution comment at lines 4381-4383 repeats the comment at lines 4362-4364 nearly word for word, and the prepareTransaction call carries a third copy just above. Ask: keep one short comment at depositVenueId.

  • [nit] packages/perps-controller/src/PerpsController.ts:7580: Still open: the pending branch comment is broken mid-sentence ("so its persisted" / "entry stays" / "until the venue reports a snapshot.", lines 7578-7581), which looks like a leftover edit. Ask: reflow it into one or two lines.

@geositta
geositta force-pushed the TAT-4392-exchange-each-its-own branch from 776b9a4 to d89bfef Compare November 17, 2026 21:20

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@geositta
geositta requested a review from abretonc7s November 18, 2026 01:27
abretonc7s
abretonc7s previously approved these changes Nov 18, 2026

@abretonc7s abretonc7s left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: APPROVE
COMMIT: 21f7b82

Each venue now gets its own account data, batch routing, stream routes and money-movement attribution. Venue identity survives every path I traced, and missing data never becomes zero. Two nits; nothing blocking.
⚠️ NOT_CHECKED: the tests were not run (static review), and no Terminal checkout was available.

Severity file:line Problem Ask
Nit packages/perps-controller/src/PerpsController.ts:4365 The direct-mode deposit venue is read from state after two awaits, but the comment says it is captured first. Derive it from the provider that prepared the route, as withdrawals do.
Details for agents
Status Item Evidence or gap Ask
Nit PR description export inventory Omits the root export OrderDiscoveryError, BATCH_INCOMPLETE and the /utils/accountAggregation subpath. The CHANGELOG lists all three. Add them to "Breaking package compatibility".
⚠️ NOT_CHECKED Test run The claim of 7,660 passing tests at 21f7b82 was not reproduced. All 25 changed test files were read, none were run. None (reviewer-side).
⚠️ NOT_CHECKED Terminal consumer No Terminal reference checkout was supplied, so the "no dependency at b61ee0d" note is unverified. None (reviewer-side).
⚠️ NOT_CHECKED HyperLiquid stream completeness at runtime requireCompleteAccount assumes every configured DEX publishes a slice, even one where the user holds nothing. This holds in unit tests but was not checked against a live venue. Cover it in TAT-4407 QA.

Diff scope: all 51 files serve TAT-4392 or its tests. tsc-suppressions.json drops one stale TS2304 entry, which lint:tsc:check requires after the test fix (scripts/lib/tsc-suppressions.ts:352). Mobile 33b5bb61 and Extension 46c84f23 consumers match the CHANGELOG BREAKING list and the ticketed client plan.

➖ 11 rules not applicable to this diff; full ledger in the run artifacts: artifacts/review-ledger.md.

Diff scope

File Ticket AC or required test Scope justification or finding
packages/perps-controller/CHANGELOG.md TAT-4392 consumer communication Unreleased entries for the BREAKING account, route, batch and default-provider changes; released sections untouched.
packages/perps-controller/README.md TAT-4392 documentation Adds the 'Per-exchange account data' consumer section.
packages/perps-controller/docs/architecture.md TAT-4392 documentation Provider table, balance contract, error code count (105, verified) and OrderDiscoveryError updated.
packages/perps-controller/src/PerpsController.ts TAT-4392: per-venue balance, positions and charts Writes perpsBalances per venue, account-scoped stream ownership, isCurrent for aggregate results, preload bucketing, batch refusal narrowing, deposit venue attribution. Nit at line 4365.
packages/perps-controller/src/aggregation/SubscriptionMultiplexer.ts TAT-4392: per-venue balance, positions and charts Per-subscription account cache, onError isolation, accountId/requireCompleteAccount forwarding.
packages/perps-controller/src/errors.ts TAT-4392: per-venue balance, positions and charts OrderDiscoveryError for strict open-order discovery used by venue-attributed cancel.
packages/perps-controller/src/index.ts TAT-4392: per-venue balance, positions and charts Exports the new account entry/metadata types, ClosePositionsTarget and OrderDiscoveryError.
packages/perps-controller/src/perpsErrorCodes.ts TAT-4392: per-venue balance, positions and charts Adds BATCH_INCOMPLETE for merged multi-venue batches.
packages/perps-controller/src/providers/AggregatedPerpsProvider.ts TAT-4392: per-venue balance, positions and charts Account fan-out and stream, venue-grouped cancel/close, explicit stream routes, per-venue routes and fee scope.
packages/perps-controller/src/providers/HyperLiquidProvider.ts TAT-4392: per-venue balance, positions and charts throwOnUnavailable for account/positions/orders and tagged close targets so aggregation can mark HL unavailable.
packages/perps-controller/src/providers/LighterProvider.ts TAT-4392: per-venue balance, positions and charts Account scope guard, null on wallet rebind, strict discovery, best-effort cross-margin summary.
packages/perps-controller/src/services/AccountService.ts TAT-4392: per-venue balance, positions and charts Withdrawal record venue attribution.
packages/perps-controller/src/services/DepositService.ts TAT-4392: per-venue balance, positions and charts Deposit route selection by explicit venue or routing default; fails closed.
packages/perps-controller/src/services/HyperLiquidSubscriptionService.ts TAT-4392: per-venue balance, positions and charts requireCompleteAccount gating and completeness in the account hash.
packages/perps-controller/src/services/RewardsIntegrationService.ts TAT-4392: per-venue balance, positions and charts Reserved subscription notional so fan-out venues cannot spend the same allowance.
packages/perps-controller/src/services/ServiceContext.ts TAT-4392: per-venue balance, positions and charts getOpenOrders accepts params for strict discovery.
packages/perps-controller/src/services/TradingService.ts TAT-4392: per-venue balance, positions and charts Selection helpers, discovery failure accounting, per-venue fee routes for batch close.
packages/perps-controller/src/types/index.ts TAT-4392: per-venue balance, positions and charts New optional contract fields and types for per-venue data and routing.
packages/perps-controller/src/utils/accountAggregation.ts TAT-4392: per-venue balance, positions and charts Decimal-safe combined totals and completeness metadata.
packages/perps-controller/src/utils/accountUtils.ts TAT-4392: per-venue balance, positions and charts getCaipAccountAddress and shared decimal totals in aggregateAccountStates.
packages/perps-controller/src/utils/cancelOrders.ts TAT-4392: per-venue balance, positions and charts Shared cancel selection and unrouted refusal used by controller and TradingService.
packages/perps-controller/src/utils/closePositions.ts TAT-4392: per-venue balance, positions and charts Shared close selection used by controller, TradingService and both providers.
packages/perps-controller/src/utils/feeSupport.ts TAT-4392: per-venue balance, positions and charts hasFeeSetter shared by aggregated provider and TradingService.
packages/perps-controller/src/utils/standaloneInfoClient.ts TAT-4392: per-venue balance, positions and charts Strict standalone DEX reads for throwOnUnavailable.
packages/perps-controller/tests/public-api-types.ts Required test: consumer-style export assertions Type assertions through the package entrypoint for the new exports.
packages/perps-controller/tests/src/PerpsController.configuration.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/PerpsController.default-provider.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/PerpsController.lifecycle.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/PerpsController.operations.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/PerpsController.subscriptions.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/aggregation/SubscriptionMultiplexer.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.discovery.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/providers/HyperLiquidProvider.error-handling.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/providers/HyperLiquidProvider.history.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/providers/HyperLiquidProvider.standalone.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/providers/HyperLiquidProvider.trading.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/providers/LighterProvider.order-validation.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/providers/LighterProvider.reads-and-orders.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/providers/LighterProvider.streaming-and-session.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/services/AccountService.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/services/DepositService.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/services/HyperLiquidSubscriptionService.cache.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/services/RewardsIntegrationService.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/services/TradingService.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/utils/accountAggregation.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/utils/accountUtils.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/utils/cancelOrders.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/utils/closePositions.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
packages/perps-controller/tests/src/utils/feeSupport.test.ts Required test Covers the changed behavior in the matching source file (inspected, not executed).
tsc-suppressions.json Required by test change Drops one stale TS2304 suppression for AggregatedPerpsProvider.test.ts; scripts/lib/tsc-suppressions.ts:352 fails lint:tsc:check on stale suppressions, so the test edit forces it. Not a tooling-config change.

Additional findings

  • [nit] packages/perps-controller/CHANGELOG.md: The PR description's 'Breaking package compatibility' export inventory lists PerpsProviderAccountStateEntry, AccountAggregateMetadata, ClosePositionsTarget and three utils subpaths, but omits the new root export OrderDiscoveryError, the BATCH_INCOMPLETE code and the /utils/accountAggregation subpath. The CHANGELOG has all of them. Ask: add them to the PR description so the consumer inventory matches the package.

// The chosen route names the venue in aggregated mode; in direct mode
// the active provider is the venue. Captured before any asynchronous
// work, never relabeled later.
const directDepositVenue =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit. The direct-mode deposit venue comes from this.state.activeProvider after await #getActiveProviderWhenReady() and await prepareTransaction(), while the comment says it is captured before any asynchronous work. Withdrawal attribution (AccountService.ts) derives the venue from the provider instance instead. If the active provider changes in that window, the record names a venue that did not prepare the route. Ask: return route.providerId ?? provider.protocolId (narrowed with isPerpsProviderType) from DepositService.prepareTransaction, matching the withdrawal path, or fix the comment.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8a0b597. DepositService.prepareTransaction now resolves route.providerId ?? provider.protocolId, narrowed with isPerpsProviderType, and the controller uses that result without falling back to mutable state.activeProvider. Updated the comment and added regression coverage for provider changes during preparation and unresolved venues.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

weitingsun pushed a commit to DreamBoysYJ/metamask-mobile that referenced this pull request Nov 18, 2026
…ask#39846)

## **Description**

Adds ready-made component-view presets for a user with Hyperliquid and
Lighter both enabled
([TAT-4387](https://consensyssoftware.atlassian.net/browse/TAT-4387)),
so the Lighter UI tickets don't each build aggregated mode by hand.

`perpsTwoExchangeState(scenario)` returns `{ overrides, streamOverrides
}` for any perps renderer. Scenarios: `bothFunded`, `oneFunded`,
`sameMarketOnBoth` and `lighterDown`. `withLighterBuildEnabled()` sets
and restores the Lighter env var the screens also need. The aggregated
test in `PerpsBalanceOrderView.view.test.tsx` now uses
`sameMarketOnBoth`, and the presets are documented in
`docs/testing/component-view-tests.md`.

The scenarios are synthetic fixtures built from fields the installed
`perps-controller` supports, not snapshots of what it emits.
[core#11461](MetaMask/core#11461) (TAT-4392)
adds per-exchange account state, which will replace how "Lighter down"
is modeled here. A `@ts-expect-error` in `perpsTwoExchangePresets.ts`
makes `yarn lint:tsc` fail when the package is bumped, so the presets
get updated then.

## Test layer placement

Unit for the presets (`perpsTwoExchangePresets.test.ts`). Component view
for the migrated `PerpsBalanceOrderView` test.

## **Changelog**

CHANGELOG entry: null

## **Related issues**

Fixes:
[TAT-4387](https://consensyssoftware.atlassian.net/browse/TAT-4387)
Related:
[TAT-4392](https://consensyssoftware.atlassian.net/browse/TAT-4392)

## **Manual testing steps**

N/A — test-only change.

## **Screenshots/Recordings**

### **Before**

N/A — no UI changes.

### **After**

N/A — no UI changes.

## **Pre-merge author checklist**

- [x] I've followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile
Coding
Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've completed the PR template to the best of my ability
- [x] I've included tests if applicable
- [x] I've documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [x] I've applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

#### Performance checks (if applicable)

N/A, test-only change with no runtime code.

- [x] I've tested on Android
  - Ideally on a mid-range device; emulator is acceptable
- [x] I've tested with a power user scenario
- Use these [power-user
SRPs](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/edit-v2/401401446401?draftShareId=9d77e1e1-4bdc-4be1-9ebb-ccd916988d93)
to import wallets with many accounts and tokens
- [x] I've instrumented key operations with Sentry traces for production
performance metrics
- See [`trace()`](/app/util/trace.ts) for usage and
[`addToken`](/app/components/Views/AddAsset/components/AddCustomToken/AddCustomToken.tsx#L274)
for an example

For performance guidelines and tooling, see the [Performance
Guide](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/400085549067/Performance+Guide+for+Engineers).

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.


[TAT-4387]:
https://consensyssoftware.atlassian.net/browse/TAT-4387?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
[TAT-4387]:
https://consensyssoftware.atlassian.net/browse/TAT-4387?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Test-only fixtures and documentation; no production runtime or
security-sensitive paths change.
> 
> **Overview**
> Introduces shared **two-exchange** component-view fixtures so Perps
tests can render Hyperliquid + Lighter in aggregated mode without
hand-building engine and stream state.
> 
> `perpsTwoExchangeState(scenario)` returns `{ overrides,
streamOverrides }` for `bothFunded`, `oneFunded`, `sameMarketOnBoth`,
and `lighterDown`, including remote Lighter feature flags and combined
balances. `withLighterBuildEnabled()` toggles
`MM_PERPS_LIGHTER_PROVIDER_ENABLED` per describe block. Unit tests cover
preset math and flag restore behavior; `PerpsBalanceOrderView.view.test`
uses `sameMarketOnBoth` for the aggregated Lighter market case. Docs and
`babel.config.tests.js` register the new helpers/presets. A
`@ts-expect-error` on `AccountState['providerStates']` is meant to force
preset updates when core ships per-exchange availability.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
88bbe4a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
@Bigshmow Bigshmow self-assigned this Nov 18, 2026
@Bigshmow

Copy link
Copy Markdown
Contributor

Nice work on the fan-out. One thing in subscribeToAccount: a stream opened without accountId always counts as the selected account, so after a switch the old stream can write perpsBalances/accountState back. For example, Lighter rebinds and emits null, the mux re-emits the old account's cached HL snapshot, and the pending rule keeps it. Could we capture the selected address in the open callback and check it on each emission, plus a test that emits from the old stream after the switch?

geositta and others added 20 commits November 18, 2026 16:27
<!--
Thanks for your contribution! Take a moment to answer these questions so
that reviewers have the information they need to properly understand
your changes:

* What is the current state of things and why does it need to change?
* What is the solution your changes offer and how does it work?
* Are there any changes whose purpose might not obvious to those
unfamiliar with the domain?
* If your primary goal was to update one package but you found you had
to update another one along the way, why did you do so?
* If you had to upgrade a dependency, why did you do so?
-->

<!--
Are there any issues that this pull request is tied to?
Are there other links that reviewers should consult to understand these
changes better?
Are there client or consumer pull requests to adopt any breaking
changes?

For example:

* Fixes #12345
* Related to #67890
-->

- [ ] I've updated the test suite for new or updated code as appropriate
- [ ] I've updated documentation (JSDoc, Markdown, etc.) for new or
updated code as appropriate
- [ ] I've communicated my changes to consumers by [updating changelogs
for packages I've
changed](https://github.com/MetaMask/core/tree/main/docs/processes/updating-changelogs.md)
- [ ] I've introduced [breaking
changes](https://github.com/MetaMask/core/tree/main/docs/processes/breaking-changes.md)
in this PR and have prepared draft pull requests for clients and
consumer packages to resolve them

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking account subscription callback and `perpsBalances` semantics
affect multi-venue portfolio UI; cancel-order filtering changes prevent
accidental mass cancels but alter batch behavior.
>
> **Overview**
> **Multi-venue account streams and aggregation** now distinguish
**pending** venues (no first snapshot yet, including an initial `null`)
from **unavailable** ones, and reject venues whose additive balance
fields are missing or non-finite instead of folding them into combined
totals. `subscribeToAccount` callbacks receive an optional second
**`AccountAggregateMetadata`** argument even when `account` is `null`,
and **`PerpsController`** only clears `perpsBalances` for explicitly
unavailable venues on a null aggregate—pending venues keep persisted
entries and `accountValue1dAgo` history. Aggregation math in
**`accountAggregation`** / **`accountUtils`** is centralized on
decimal-safe **`aggregateAccountTotals`** with margin-weighted combined
RoE.
>
> **Order cancellation** adds **`CancelOrdersParams.orders`** (`{
orderId, providerId }`) so colliding IDs across venues cancel only the
intended venue; legacy **`orderIds`** still match every venue. Empty
**`orders`**, **`orderIds`**, or **`symbols`** no longer fall through to
cancel-all.
>
> **Stream routing**: an explicit but unregistered **`providerId`** on
candles/OI/order book subscriptions reports via **`onError`** and
returns a no-op cleanup instead of subscribing through a stub provider.
Cancel results can include **`providerId`** per item. Changelog/README
and type-level tests reflect the breaking account callback and balance
semantics.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3a5a66d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Cursor <cursoragent@cursor.com>
- Commit the cancel-selection and fee-setter helpers that 1e20226
  imports but never added, with their tests.
- Add resolveCloseSelection so targets > closeAll > symbols precedence
  lives in one place instead of seven.
- Fold Unreleased "Fixed" entries for behaviour that never shipped in
  24.0.0 into the Added/Changed entries for the same feature, and list
  PerpsProvider.getProviderIds under Added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e targets, review fixes

- Aggregated account streams request requireCompleteAccount; HyperLiquid
  emits null until every configured DEX and the spot balance have loaded,
  so a failed DEX subscription keeps the aggregate partial.
- An empty closePositions targets list closes nothing instead of falling
  through to close-all.
- Account streams for a non-selected accountId no longer write or delete
  perpsBalances entries.
- An unregistered explicit stream route reports a bare PROVIDER_NOT_FOUND.
- Restore the released 24.1.0 changelog section to main and move this
  PR's entries back under Unreleased.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… without casts

Pass the stream's onError handler to #resolveExplicitStreamRoute instead of a
params union checked with an `in` guard, and annotate the validated aggregate
entries' return type instead of `as const`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s out of live account state

- A HyperLiquid account is complete for `requireCompleteAccount` only when
  every configured DEX has published on the current connection. Per-DEX
  slices survive a reconnect, so the cached pre-reconnect account is no
  longer replayed or emitted as the venue's full live balance.
- A controller account stream for an explicit `accountId` other than the
  selected account now only reaches its own callback: it neither writes nor
  clears `accountState`, `lastUpdateTimestamp` or `perpsBalances`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ting in architecture

Update the AggregatedPerpsProvider row for fan-out account reads and
streams, per-venue money-movement routes, venue-grouped batch cancel and
close, and explicit stream routes. Add providerStates and aggregate to the
AccountState balance contract, and record BATCH_INCOMPLETE and
OrderDiscoveryError under Errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… and validate account ids

- HyperLiquid strict open-order discovery that only partly succeeds now
  adapts the orders it did read with the same position lookup as a complete
  read, so a whole-position TP/SL in `OrderDiscoveryError.orders` reports the
  position size instead of 0.
- Account-scope checks parse `accountId` as CAIP-10 instead of taking the
  last `:` segment. A bare address or an id with extra segments no longer
  passes as the selected wallet: the controller does not let such a stream
  write selected-account state, and Lighter rejects it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…opens, block old streams from writing or clearing selected account state after a switch, leave consumer callbacks and subscription lifecycle unchanged
…r, report partial totals when another venue’s cache is unusable, preserve single-venue snapshot shape and venue-local details
@geositta
geositta enabled auto-merge November 18, 2026 22:58
@geositta
geositta added this pull request to the merge queue Nov 18, 2026
Merged via the queue into main with commit ef6da95 Nov 18, 2026
73 checks passed
@geositta
geositta deleted the TAT-4392-exchange-each-its-own branch November 18, 2026 22:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants